package com.compass.doctor.utils;

import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Description： 统计图初始化工具类
 * Date:2023/12/13 10:46
 */
public class ChartUtils {
    /*
     *  单柱状图初始化
     */

    public static void initBarChart(BarChart chartPatients) {

        chartPatients.getDescription().setEnabled(false);//图标描述

        // 二指控制X轴Y轴同时放大
        chartPatients.setPinchZoom(false);
        //此设置为true，双击图表进行放大。
        chartPatients.setDoubleTapToZoomEnabled(false);
        //显示边框
        chartPatients.setDrawBorders(false);
        //如果设置为true，所有值都绘制在条形图的上方，而不是顶部下方。
        chartPatients.setDrawValueAboveBar(true);
        //背景阴影
        chartPatients.setDrawBarShadow(false);
        chartPatients.setHighlightFullBarEnabled(false);
        //设置为true来绘制网格背景，否则为false
        chartPatients.setDrawGridBackground(false);

        //X轴显示位置
        XAxis xLabels = chartPatients.getXAxis();
        xLabels.setPosition(XAxis.XAxisPosition.BOTTOM);
        xLabels.setDrawGridLines(false);
        xLabels.setGranularity(1f);
        /* Y轴设置 */
        YAxis leftAxis = chartPatients.getAxisLeft();
        YAxis rightAxis = chartPatients.getAxisRight();
        //不显示X轴 Y轴线条
        leftAxis.setDrawAxisLine(true);
        rightAxis.setDrawAxisLine(false);
//        leftAxis.setYOffset(0);
        //不显示右侧Y轴
        rightAxis.setEnabled(false);
        //右侧Y轴网格线设置为虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
//        leftAxis.setDrawGridLines(false);
        //设置Y左边轴显示的值 label 数量
//        leftAxis.setLabelCount(7, true);
        //设置值显示的位置，我们这里设置为显示在Y轴外面
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        //设置Y轴 与值的空间空隙 这里设置30f意为30%空隙，默认是10%
//        leftAxis.setSpaceTop(0f);
        leftAxis.setAxisMinimum(0f);//设置Y轴最小值

        //折线图例 标签 设置
        Legend legend = chartPatients.getLegend();
        legend.setForm(Legend.LegendForm.SQUARE);//图示 标签的形状。   正方形
        legend.setTextSize(11f);
        legend.setYOffset(18f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
    }


    public static void initLineChart(LineChart lineChart) {

        lineChart.getDescription().setEnabled(false);
        lineChart.setMaxVisibleValueCount(200);
        // 二指控制X轴Y轴同时放大
        lineChart.setPinchZoom(false);
        //此设置为true，双击图表进行放大。
        lineChart.setDoubleTapToZoomEnabled(false);
        //显示边框
        lineChart.setDrawBorders(false);
        //设置为true来绘制网格背景，否则为false
        lineChart.setDrawGridBackground(false);

        //X轴显示位置
        XAxis xLabels = lineChart.getXAxis();
        xLabels.setPosition(XAxis.XAxisPosition.BOTTOM);
        xLabels.setDrawGridLines(false);
        xLabels.setGranularity(1f);
        /* Y轴设置 */
        YAxis leftAxis = lineChart.getAxisLeft();
        YAxis rightAxis = lineChart.getAxisRight();
        //不显示X轴 Y轴线条
        leftAxis.setDrawAxisLine(true);
        rightAxis.setDrawAxisLine(false);
        leftAxis.setYOffset(0);
        //不显示右侧Y轴
        rightAxis.setEnabled(false);
        //右侧Y轴网格线设置为虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置值显示的位置，我们这里设置为显示在Y轴外面
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        //设置Y轴 与值的空间空隙 这里设置30f意为30%空隙，默认是10%
        leftAxis.setSpaceTop(0f);
        leftAxis.setAxisMinimum(0f);//设置Y轴最小值
        //折线图例 标签 设置
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.SQUARE);//图示 标签的形状。   正方形
        legend.setTextSize(11f);
        legend.setYOffset(13f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);


    }

    /*
     * 饼图初始化
     *  isHole 是圆环还是实心
     * */
    public static void initSexPieChart(PieChart sexPieChart) {

        sexPieChart.setUsePercentValues(true);
        sexPieChart.getDescription().setEnabled(false);

        sexPieChart.setDragDecelerationFrictionCoef(0.95f);
        sexPieChart.setCenterText(generateCenterSpannableText());
        //设置为true，使饼图中心为空
        sexPieChart.setDrawHoleEnabled(true);
        sexPieChart.setHoleColor(Color.WHITE);
        sexPieChart.setTransparentCircleColor(Color.WHITE);
        sexPieChart.setTransparentCircleAlpha(110);
        sexPieChart.setHoleRadius(55f);
        sexPieChart.setTransparentCircleRadius(60f);
        sexPieChart.setDrawCenterText(true);
        sexPieChart.setCenterTextSize(10f);
        sexPieChart.setRotationAngle(0);
        sexPieChart.setRotationEnabled(true);
        sexPieChart.setHighlightPerTapEnabled(true);


        Legend l = sexPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setTextSize(11f);
        l.setYOffset(13f);

        sexPieChart.setEntryLabelColor(Color.WHITE);
        sexPieChart.setEntryLabelTextSize(12f);
    }

    private static SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("性别分布\nGENDER STATISTICS");
        s.setSpan(new RelativeSizeSpan(1.4f), 0, 4, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 4, s.length(), 0);

        return s;
    }


    /*
     * 饼图初始化
     *  isHole 是圆环还是实心
     * */
    public static void initHalfPieChart(PieChart agePieChart) {

        agePieChart.setUsePercentValues(true);//设置使用百分比
        agePieChart.getDescription().setEnabled(false);

        agePieChart.setDragDecelerationFrictionCoef(0.95f);
        agePieChart.setCenterText(generateAgeSpannableText());
        //设置为true，使饼图中心为空
        agePieChart.setDrawHoleEnabled(true);
        agePieChart.setHoleColor(Color.WHITE);
        agePieChart.setTransparentCircleColor(Color.WHITE);
        agePieChart.setTransparentCircleAlpha(110);
        agePieChart.setHoleRadius(55f);
        agePieChart.setTransparentCircleRadius(60f);
        agePieChart.setDrawCenterText(true);
        agePieChart.setCenterTextSize(10f);
        agePieChart.setRotationEnabled(false);
        agePieChart.setHighlightPerTapEnabled(true);
        agePieChart.setMaxAngle(180f); // HALF CHART
        agePieChart.setRotationAngle(180f);
        agePieChart.setCenterTextOffset(0, -20);
        Legend l = agePieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setTextSize(12f);
        l.setYOffset(13f);

        agePieChart.setEntryLabelColor(Color.WHITE);
        agePieChart.setEntryLabelTextSize(12f);
    }

    private static SpannableString generateAgeSpannableText() {
        SpannableString s = new SpannableString("当月业务");
        s.setSpan(new RelativeSizeSpan(1.4f), 0, s.length(), 0);
        return s;
    }


    /*
     * 饼图初始化
     *  isHole 是圆环还是实心
     * */
    public static void initPieChart(PieChart typePieChart) {
        typePieChart.setUsePercentValues(true);//设置使用百分比
        typePieChart.getDescription().setEnabled(false);

        typePieChart.setDragDecelerationFrictionCoef(0.95f);
        typePieChart.setCenterText(generateDiseasesSpannableText());
        //设置为true，使饼图中心为空
        typePieChart.setDrawHoleEnabled(true);
        typePieChart.setHoleColor(Color.WHITE);
        typePieChart.setTransparentCircleColor(Color.WHITE);
        typePieChart.setTransparentCircleAlpha(110);
        typePieChart.setHoleRadius(55f);
        typePieChart.setTransparentCircleRadius(60f);
        typePieChart.setDrawCenterText(true);
        typePieChart.setCenterTextSize(10f);
        typePieChart.setRotationEnabled(false);
        typePieChart.setHighlightPerTapEnabled(true);

        typePieChart.setRotationAngle(180f);

        Legend l = typePieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setTextSize(12f);
        l.setYOffset(13f);

        typePieChart.setEntryLabelColor(Color.WHITE);
        typePieChart.setEntryLabelTextSize(12f);

    }


    private static SpannableString generateDiseasesSpannableText() {

        SpannableString s = new SpannableString("问诊类型分布");
        s.setSpan(new RelativeSizeSpan(1.4f), 0, s.length(), 0);

        return s;
    }


    /*
     *  双柱状图初始化
     * */

    public static void setTwoBarChart(BarChart barChart, List<String> xAxisValue, List<Float> yAxisValue1, List<Float> yAxisValue2, String bartilte1, String bartitle2) {
        barChart.getDescription().setEnabled(false);//设置描述
        barChart.setPinchZoom(true);//设置按比例放缩柱状图
        barChart.setExtraBottomOffset(10);
        barChart.setExtraTopOffset(30);

        //x坐标轴设置
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawLabels(true);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(xAxisValue.size());
        xAxis.setCenterAxisLabels(true);//设置标签居中
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xAxisValue));

        /* Y轴设置 */
        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setValueFormatter(new MyValueFormatter());
        YAxis rightAxis = barChart.getAxisRight();
        //不显示X轴 Y轴线条
        leftAxis.setDrawAxisLine(true);
        rightAxis.setDrawAxisLine(false);
        //不显示右侧Y轴
        rightAxis.setEnabled(false);
        //右侧Y轴网格线设置为虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置值显示的位置，我们这里设置为显示在Y轴外面
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        //设置Y轴 与值的空间空隙 这里设置30f意为30%空隙，默认是10%
        leftAxis.setSpaceTop(0f);
        leftAxis.setAxisMinimum(0);//设置Y轴最小值

        //设置坐标轴最大最小值
        Float yMin1 = Collections.min(yAxisValue1);
        Float yMin2 = Collections.min(yAxisValue2);
        Float yMax1 = Collections.max(yAxisValue1);
        Float yMax2 = Collections.max(yAxisValue2);
        Float yMin = Double.valueOf((yMin1 < yMin2 ? yMin1 : yMin2) * 0.1).floatValue();
        Float yMax = Double.valueOf((yMax1 > yMax2 ? yMax1 : yMax2) * 1.1).floatValue();
        leftAxis.setAxisMaximum(yMax + 3);
        leftAxis.setAxisMinimum(yMin);

        barChart.getAxisRight().setEnabled(false);


        //图例设置
        Legend legend = barChart.getLegend();
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);

        //设置柱状图数据
        setTwoBarChartData(barChart, xAxisValue, yAxisValue1, yAxisValue2, bartilte1, bartitle2);

        barChart.animateX(1000);//数据显示动画，从左往右依次显示
        barChart.invalidate();
    }

    /**
     * 设置柱状图数据源
     */
    private static void setTwoBarChartData(BarChart barChart, List<String> xAxisValue, List<Float> yAxisValue1, List<Float> yAxisValue2, String bartilte1, String bartitle2) {
        float groupSpace = 0.04f;
        float barSpace = 0.03f;
        float barWidth = 0.45f;
        // (0.45 + 0.03) * 2 + 0.04 = 1，即一个间隔为一组，包含两个柱图 -> interval per "group"

        ArrayList<BarEntry> entries1 = new ArrayList<>();
        ArrayList<BarEntry> entries2 = new ArrayList<>();

        for (int i = 0, n = yAxisValue1.size(); i < n; ++i) {
            entries1.add(new BarEntry(i, yAxisValue1.get(i)));
            entries2.add(new BarEntry(i, yAxisValue2.get(i)));
        }

        BarDataSet dataset1, dataset2;

        if (barChart.getData() != null && barChart.getData().getDataSetCount() > 0) {
            dataset1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            dataset2 = (BarDataSet) barChart.getData().getDataSetByIndex(1);
            dataset1.setValues(entries1);
            dataset2.setValues(entries2);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            dataset1 = new BarDataSet(entries1, bartilte1);
            dataset2 = new BarDataSet(entries2, bartitle2);

            dataset1.setColor(Color.rgb(92, 141, 242));
            dataset2.setColor(Color.rgb(217, 231, 255));

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(dataset1);
            dataSets.add(dataset2);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);
            data.setValueFormatter(new MyValueFormatter());

            barChart.setData(data);
        }

        barChart.getBarData().setBarWidth(barWidth);
        barChart.getXAxis().setAxisMinimum(0);
        // barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
        barChart.getXAxis().setAxisMaximum(barChart.getBarData().getGroupWidth(groupSpace, barSpace) * xAxisValue.size() + 0);
        barChart.groupBars(0, groupSpace, barSpace);
    }
}
